﻿#if  NET6_0_OR_GREATER 
using Microsoft.AspNetCore.Http;
using System;
using System.Threading.Tasks;
using T.ServiceFramework.Spi;

namespace T.SF.Console
{
    public class CrosMiddleware
    {
        private readonly RequestDelegate _next;
        public CrosMiddleware(RequestDelegate next)
        {
            _next = next;
        }

        public async Task Invoke(HttpContext context)
        {
            DateTime start = DateTime.Now;

            context.Response.OnCompleted(() =>
            {
                DateTime end = DateTime.Now;
                string ip = string.Empty;
                if (context.Request.Headers.ContainsKey("X-Forwarded-For"))
                {
                    ip = context.Request.Headers["X-Forwarded-For"];
                }
                else if (context.Request.Headers.ContainsKey("X-Real-IP"))
                {
                    ip = context.Request.Headers["X-Real-IP"];
                }
                else
                {
                    ip = context.Connection?.RemoteIpAddress?.ToString();
                }

                string userAgent = string.Empty;
                if (context.Request.Headers.ContainsKey("User-Agent"))
                {
                    userAgent = context.Request.Headers["User-Agent"];
                }
                double duration = (end - start).TotalMilliseconds;

                string log = string.Format("{0}{1},{2},{3}ms,{4},{5}", context.Request.Path, context.Request.QueryString.Value, ip, duration, context.Response.StatusCode, userAgent);
                if (duration < 2000)
                {
                    TSFLogger.Info(log);
                }
                else
                {
                    TSFLogger.Warn(log, true);
                }

                return Task.CompletedTask;
            });

            /*
            Access-Control-Allow-Credentials: true
            Access-Control-Allow-Headers: X-PJAX,X-PJAX-Container,Cache-Control, Pragma, Origin, Authorization, Content-Type,x-requested-with,X-Token
            Access-Control-Allow-Methods: GET, POST, PUT, DELETE, OPTIONS
             */
            context.Request.EnableBuffering();
            //context.Response.Headers.Add("Content-Type", "application/json");
            context.Response.Headers.Add("Access-Control-Allow-Credentials", "true");
            context.Response.Headers.Add("Access-Control-Allow-Headers", "X-PJAX,X-PJAX-Container,Cache-Control, Pragma, Origin, Authorization, Content-Type,x-requested-with,X-Token");
            context.Response.Headers.Add("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS");
            string Origin = context.Request.Headers["Origin"];
            if (string.IsNullOrEmpty(Origin) == false)
                context.Response.Headers.Add("Access-Control-Allow-Origin", Origin);

            await _next.Invoke(context);
        }
    }
}

#endif
